package com.binvshe.binvshe.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.ParamKey;
import com.binvshe.binvshe.app.home.ClassEvent;
import com.binvshe.binvshe.app.home.CommentFragment;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.mine.view.CommentDialog;
import com.bumptech.glide.Glide;
import com.cncn.youmengsharelib.ShareData;
import com.cncn.youmengsharelib.ShareListener;
import com.cncn.youmengsharelib.SharePlatform;
import com.f2prateek.dart.Dart;
import com.f2prateek.dart.InjectExtra;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.ogaclejapan.smarttablayout.utils.v4.Bundler;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.share.BaseShareFragment;
import com.pachong.android.framework.share.SharePlatformsFragment;
import com.pachong.android.frameworkbase.utils.DateTimeUtil;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;

import butterknife.Bind;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import jp.wasabeef.glide.transformations.BlurTransformation;

public class DetailActivity extends BaseActivity {

    @Bind(R.id.mImgHead)
    ImageView mImgHead;
    @Bind(R.id.mBtnEnrol)
    Button mBtnEnrol;

    @Bind(R.id.tvTitle)
    TextView mTvTitle;
    @Bind(R.id.tvTime)
    TextView mTvTime;
    @Bind(R.id.tvActPlace)
    TextView mTvActPlace;
    @Bind(R.id.tvPrice)
    TextView mTvPrice;
    @Bind(R.id.civCompanyHead)
    CircleImageView mCivCompanyHead;
    @Bind(R.id.tvCompanyName)
    TextView mTvCompanyName;
    @Bind(R.id.vpTabAcitivity)
    SmartTabLayout mVpTabAcitivity;
    @Bind(R.id.vpActivity)
    ViewPager mVpActivity;

    @Bind(R.id.viewBG)
    ImageView mViewBG;

    @InjectExtra(KEY_ACTIVITY_ID)
    int mActivityId;

    private static final int shareReqCode = 623;

    @InjectExtra(KEY_HEADERURL)
    String mHeaderUrl;

    @InjectExtra(KEY_TITLEL)
    String mTitle;
    private static final String KEY_ACTIVITY_ID = "key_activity_id";
    private static final String KEY_HEADERURL = "key_headerurl";
    private static final String KEY_TITLEL = "key_title";
//    @Bind(R.id.moreRl)
//    RelativeLayout mMoreRl;
    @Bind(R.id.ivShareActivity)
    ImageView mIvShareActivity;
    @Bind(R.id.imageView6)
    ImageView mImageView6;
    @Bind(R.id.mBtnShowMap)
    Button mMBtnShowMap;
    @Bind(R.id.mFlEnrol)
    FrameLayout mMFlEnrol;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Dart.inject(this);

        setTitle("活动详情");
        getCustomToolbar().addRightImageButton(R.mipmap.icon_sharettt, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                BaseShareFragment fragment = SharePlatformsFragment.showShareFragment(DetailActivity.this, makeActivityShareData(mTitle, mHeaderUrl));
                fragment.setShareListener(new ShareListener() {
                    @Override
                    public void onShareSuccess(Activity shareActivity, SharePlatform platform) {
                        EasyToast.showToast(DetailActivity.this, "分享成功");
                    }

                    @Override
                    public void onShareFailed(Activity shareActivity, SharePlatform platform) {
                        EasyToast.showToast(DetailActivity.this, "分享失败");
                    }

                    @Override
                    public void onShareCancel(Activity shareActivity, SharePlatform platform) {
                        EasyToast.showToast(DetailActivity.this, "分享取消");
                    }
                });
            }
        });
        hideToolbar();
//        enableBackButton();
        initVP();
        setView();
        getActivityDetails();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//        } else {
//            mMoreRl.setVisibility(View.GONE);
//        }

        //// FIXME: 2017/1/23 原底部web
//        String url = UrlCenter.ACTIVITY_DETAIL_HEADER + mActivityId;
//        CommonWebviewFragment webFragment = CommonWebviewFragment.newInstance(url);
//        getSupportFragmentManager().beginTransaction().add(R.id.lytWeb, webFragment).commitAllowingStateLoss();

    }


    public static void start(Context context, int id, String headerUrl, String title) {
        Intent starter = new Intent(context, DetailActivity.class);
        starter.putExtra(KEY_ACTIVITY_ID, id);
        starter.putExtra(KEY_HEADERURL, headerUrl);
        starter.putExtra(KEY_TITLEL, title);
        context.startActivity(starter);
    }

    private void initVP() {
        FragmentPagerItems.Creator items = FragmentPagerItems.with(this)
                .add("活动详情", ActivityDetailsFragment.class, new Bundler().putInt(KEY_ACTIVITY_ID, mActivityId).get())
                .add("活动评论", CommentFragment.class,
                        new Bundler().putInt("key_target_id", mActivityId).putString("TYPE", "activity").get());
        FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(getSupportFragmentManager(), items.create());
        mVpActivity.setAdapter(adapter);
        mVpTabAcitivity.setViewPager(mVpActivity);
    }

    public static ShareData makeActivityShareData(String title, String imgUrl) {
        String imageUrl = imgUrl;
        String targetUrl = "http://pic24.nipic.com/20121025/11197132_095434613172_2.jpg";
        return new ShareData(imageUrl, title, title, targetUrl);
    }


    private void setView() {
        IML.load(this, mImgHead, mHeaderUrl);
        Glide.with(this)
                .load(mHeaderUrl)
                .crossFade(1000)
                .bitmapTransform(new BlurTransformation(this, 23, 4)) // “23”：设置模糊度(在0.0到25.0之间)，默认”25";"4":图片缩放比例,默认“1”。
                .into(mViewBG);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.act_detail, null);

        return rootView;
    }


    public void getActivityDetails() {
        IHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.ACTIVITY_DETAILS, mActivityId);
        request.get(url, null, new DataRequestListener<ActivityEntity>(ActivityEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(ActivityEntity o) {
                super.onSuccess(o);
                mActivityEntity = o;
                EventBus.getDefault().post(new ActivityEvent.DetailsEvent(o));
                mTvTitle.setText(o.getName());

                String beginTime = DateTimeUtil.getDateStr(new Date(o.getBegin_time()));
                String endTime = DateTimeUtil.getDateStr(new Date(o.getEnd_time()));
                mTvTime.setText(o.getDuration());
                mTvActPlace.setText(o.getAddress());
                mTvPrice.setText(o.getPrice());
                if (o.isExpired()) {
                    mBtnEnrol.setText("已结束");
                    mBtnEnrol.setClickable(false);
                    mBtnEnrol.setBackgroundColor(Color.parseColor("#D3D3D3"));
                    mMFlEnrol.setBackgroundResource(R.drawable.bg_btn_gray);
                }
//                IML.load(DetailActivity.this, mCivCompanyHead, o.getSponsor_avatar());
                IML.load(DetailActivity.this, mCivCompanyHead, mHeaderUrl);

                mTvCompanyName.setText(o.getSponsor());
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    ActivityEntity mActivityEntity;

    @OnClick({R.id.mBtnEnrol, R.id.mBtnShowMap, R.id.btnComment, R.id.ivShareActivity, R.id.imageView6})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mBtnEnrol:
                SelectGoodsActivity.start(this, mActivityId);

                break;
            case R.id.mBtnShowMap:
                MapActivity.start(this, mActivityEntity);
                break;
            case R.id.btnComment:
                showCommentDialog("activity");
                break;
            case R.id.ivShareActivity:
                BaseShareFragment fragment = SharePlatformsFragment.showShareFragment(DetailActivity.this, makeActivityShareData(mTitle, mHeaderUrl));
                fragment.setShareListener(new ShareListener() {
                    @Override
                    public void onShareSuccess(Activity shareActivity, SharePlatform platform) {
                        EasyToast.showToast(DetailActivity.this, "分享成功");
                    }

                    @Override
                    public void onShareFailed(Activity shareActivity, SharePlatform platform) {
                        EasyToast.showToast(DetailActivity.this, "分享失败");
                    }

                    @Override
                    public void onShareCancel(Activity shareActivity, SharePlatform platform) {
                        EasyToast.showToast(DetailActivity.this, "分享取消");
                    }
                });

                break;
            case R.id.imageView6:
                finish();

                break;
        }
    }

    private void showCommentDialog(final String type) {
        CommentDialog commentDialog = CommentDialog.newInstance("评论", "写评论", 4, true);
        commentDialog.show(getSupportFragmentManager(), "tag");
        commentDialog.setOnClickable(new CommentDialog.CommentClickable() {

            @Override
            public void btnEnter(String comment) {
                MyHttpRequest request = new MyHttpRequest(DetailActivity.this);
                String url = String.format(UrlCenter.COMMENT, type, mActivityId);
                JSONObject jobj = new JSONObject();
                try {
                    jobj.put(ParamKey.CONTENT, comment);
                    request.post(url, jobj, new DataRequestListener<String>(String.class) {
                        @Override
                        public void onStart(Context context, String url) {
                            enableProgress(false);
                            super.onStart(context, url);
                        }

                        @Override
                        public void onSuccess(String str) {
                            super.onSuccess(str);
                            EventBus.getDefault().post(new ClassEvent.RefreshEvent());
                        }

                        @Override
                        public void onFailure(Throwable t, int errorNo, String strMsg) {
                            super.onFailure(t, errorNo, strMsg);
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick(R.id.ivShareActivity)
    public void onClick() {
    }
}
